#/bin/sh

if [[ $1 == prod ]];then
  env=prod
elif [[ $1 == test ]];then
  env=test
else
  echo "参数输入有误，正确的格式为>>> sh $0  sh $0 [test|prod]"
  exit
fi

table=bbt_jd_trade
outdir=$(pwd)/${env}
mkdir -p ${outdir}
drdsLog=${env}-drds.log
importSh=${env}-mysql-import.sh
importLog=${env}-mysql-import.log

echo "正在删除历史生产的数据..."
echo "rm -rf ${outdir}" || sh

echo "初始化日志+导入文件"
echo "#/bin/sh" > ${importSh}
echo "importLog=mysql-import.log" >>${importSh}
echo 'echo "" > ${importLog}' >> ${importSh}
echo "" > ${drdsLog}

echo "即将遍历文件名称..."
fileNames=$(ls ./ | grep -e 'sql$')
for tmpFile in $fileNames
do
	echo "正在处理文件$tmpFile"
	arrName=(${tmpFile//[#.]/ })
	if (( ${#arrName[@]} != 3 ));then
             echo   "异常文件$tmpFile,实际长度是${#arrName[@]}"
             continue
        fi

	 
        shopId=${arrName[0]}
        tmpNick=${arrName[1]}
	arrDrds=$(java -jar /bbtjd/bbt-data-trade.jar ${env} ${table} ${shopId})
 	echo "java命令执行得到的分表结果:$arrDrds"
	

	envTableNick=(${arrDrds}) 
        if (( ${#envTableNick[@]} != 6 ));then
             echo   "java的分表异常,实际长度是${#envTableNick[@]}"
             continue
        fi
	ip=${envTableNick[0]}
	username=${envTableNick[1]}
        password=${envTableNick[2]}
	desDbName=${envTableNick[3]}
	desTableName=${envTableNick[4]}
	hash=${envTableNick[5]}

	echo "ip=${ip},username=${username},password=${password},db=$desDbName,table=$desTableName,shopId=$shopId,tmpNick=$tmpNick,tmpFile=${tmpFile}" >> drds.log

	outFile=${outdir}/${table}#${tmpFile}	
	echo "sed   -e  's/INSERT INTO/INSERT IGNORE INTO/g' -e  's/\`${table}\`/\`${desTableName}\`/g' -e  's/'${tmpNick}'/'${shopId}'/g' ${tmpFile}  1>${outFile}" | sh
	
	echo 'startTimeCmd=$(date +%s)' >>${importSh}
	echo "mysql -h ${ip} -u${username} -p${password} ${desDbName}  <${outFile};" >>${importSh}
	echo 'endTimeCmd=$(date +%s)'  >>${importSh}
	echo "echo '${outFile}' >>${importLog}" >>${importSh}
	echo 'echo "结束t=${endTimeCmd},开始t=${startTimeCmd},耗时=$(expr ${endTimeCmd} - ${startTimeCmd})" >> ${importLog}' >>${importSh}
done
